from fastapi import APIRouter, Request, HTTPException, File, UploadFile
from fastapi.responses import StreamingResponse, JSONResponse

from pydantic import BaseModel

from database.database import engine
from sqlalchemy import text


router = APIRouter(
    prefix='/banner',
    tags = ['轮播图片']
)


def select_banner_list():
    # try:
    with engine.connect() as conn:
        sql = text(f'''
        select * from smart_sales_banner;
        ''')
        result = conn.execute(sql).fetchall()
    return result
    # except:
    #   pass


def select_banner_type(type):
    # try:
    with engine.connect() as conn:
        sql = text(f'''
        select * from smart_sales_banner where type = :type;
        ''')
        result = conn.execute(sql, [{'type': type}]).fetchall()
    return result
    # except:
    #   pass


def save_banner_info(record):
    # try:
    with engine.connect() as conn:
        sql = text(f'''
        insert into smart_sales_banner(imgUrl, hrefUrl, type) values (:imgUrl, :hrefUrl, :type);
        ''')
        conn.execute(sql, [record])
        conn.commit()
    # except:
    #   pass


def delete_banner_info(id):
    # try:
    with engine.connect() as conn:
        sql = text(f'''
        delete from smart_sales_banner where id = :id;
        ''')
        conn.execute(sql, [{"id":id}])
        conn.commit()
    # except:
    #   pass


@router.post("/list")
def banner_list(type:str=None):
    result = select_banner_type(type) if type else select_banner_list()
    result_list = [row._asdict() for row in result]
    data = {}
    data["list"] = result_list
    data["total"] = len(result_list)
    content = { "code": 0, "message": "操作成功" }
    content["data"] = data

    return JSONResponse(status_code=200, content=content)


@router.post("/save")
def banner_save(images: list[UploadFile]):
    record["hrefUrl"] = record.get("hrefUrl")
    save_banner_info(record)
    content = { "code": 0, "message": "操作成功" }
    return JSONResponse(status_code=200, content=content)


@router.delete("/delete")
def banner_delete(id: int):
    delete_banner_info(id)
    content = { "code": 0, "message": "操作成功" }
    return JSONResponse(status_code=200, content=content)